<?php

namespace App\Admin\Controllers;

use App\Admin\Extensions\Tools\Rebuild;
use App\Handlers\RedisHandler;
use App\Models\Addressee;

use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Layout\Content;
use App\Http\Controllers\Controller;
use Encore\Admin\Controllers\ModelForm;
use Illuminate\Support\Facades\DB;
use League\Csv\Exception;
use League\Csv\Reader;

class AddresseeController extends Controller
{
    use ModelForm;

    /**
     * Index interface.
     *
     * @return Content
     */
    public function index()
    {
        return Admin::content(function (Content $content) {

            $content->header('收信人管理');
            $content->description('系统每5分钟自动同步数据，如需立即同步，请点击 同步数据');
            $content->row(view('admin.ImportPopup'));

            $content->body($this->grid());
        });
    }

    /**
     * Edit interface.
     *
     * @param $id
     * @return Content
     */
    public function edit($id)
    {
        return Admin::content(function (Content $content) use ($id) {

            $content->header('收信人管理');
            $content->description('');

            $content->body($this->form()->edit($id));
        });
    }

    /**
     * Create interface.
     *
     * @return Content
     */
    public function create()
    {
        return Admin::content(function (Content $content) {

            $content->header('收信人管理');
            $content->description('');

            $content->body($this->form());
        });
    }

    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        return Admin::grid(Addressee::class, function (Grid $grid) {

            $grid->id('ID')->sortable();
            $grid->column('number', '收信人码');
//            $grid->column('type', '类型')->sortable()->display(function ($value) {
//                return config('system.ad_dress.type')[$value];
//            });
            $grid->column('num', '次数')->sortable();
            $grid->column('status', '状态')->sortable()->display(function ($value) {
                return $value == 0 ? "可用" : '不可用';
            });
            $grid->filter(function (Grid\Filter $filter) {
                $filter->like('number', '收信人码');
                $filter->equal('status', '状态')->select(config('system.task.status'));
            });

            $grid->tools(function ($tool) {
//                $tool->append(new TrashButton());
                $importButton = <<<EOF
        <a href="javascript:initLayer()" class="btn btn-sm btn-info">
        <i class="fa fa-cloud"></i>&nbsp;&nbsp;导入
        </a>
EOF;
                $tool->append(new Rebuild());
                $tool->append($importButton);
            });

        });
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        return Admin::form(Addressee::class, function (Form $form) {

            $form->display('id', 'ID');
            $form->text('number', '收信人码');
            $form->select('type', '类型')->options(config('system.ad_dress.type'))->default(AD_DRESS_THREE_TYPE);
            $form->select('status', '状态')->options(["可用" , "不可用"])->default(0);
            $form->display('created_at', '创建时间');
            $form->saved(function (Form $form) {
//                RedisHandler::rebuild($form->model()->id);
                //在加入数据之后重建一下数据
//                RedisHandler::rebuild();
                $this-> rebuild();
            });

        });
    }

    /**
     * 重建数据
     * @return array
     */
    public function rebuild()
    {
        $redisHandler = new RedisHandler();
        $redisHandler -> rebuild();
        return ['status_code' => 200, 'message' => '重建成功'];
    }


    public function import()
    {

        ini_set('memory_limit','2048M');
        ini_set('max_execution_time',3600);
        $request = \request();
        $validFields = config('system.msg_addressee.export_fields');
        $file = $request->file('file');
        $items = [];
        if (!$file->isValid()) {
            return ['status_code' => 10001, 'message' => '上传失败'];
        }
        if (!in_array($file->getMimeType(), ['text/plain'])) {
            return ['status_code' => 10002, 'message' => '请上传csv文件'];
        }
        try{
            $csv = Reader::createFromPath($file->getRealPath(), 'r')->setHeaderOffset(0);
        }catch (Exception $e){
            return ['status_code' => 10003, 'message' => '读取csv文件失败'];
        }
        foreach ($csv as $data){
            $data = array_intersect_key($data, $validFields);
            array_push($items,$data);
        }
        $chunks = array_chunk($items, 2000);
        foreach ($chunks as $chunk) {
            DB::table('addressee')->insert($chunk);

        }
        $added_amount = count($items);

        return ['status_code' => 200, 'message' => "新增{$added_amount}条"];
    }
}
